package com.sunnyebuy.merchant.servlet;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.octo.captcha.service.CaptchaService;
import com.sunnyebuy.merchant.util.SpringUtil;

/**
 * Servlet implementation class ImageServlet
 */
public class CaptchaServlet extends HttpServlet {

    private static final long serialVersionUID = -6504726465392410677L;

	private CaptchaService captchaService = (CaptchaService)SpringUtil.getBean("captchaService");
	
    public void destroy() {
        super.destroy();
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        ServletOutputStream out = response.getOutputStream();
        String captchaId = request.getSession(true).getId();
        BufferedImage challenge = (BufferedImage) captchaService.getChallengeForID(captchaId, request.getLocale());
        ImageIO.write(challenge, "jpg", out);
        out.flush();
        out.close();
    }

    public void init() throws ServletException {
    }
    
}